package com.zzh.wheelview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.zzh.wheelview.R;

import java.util.Random;

/**
 * Created by haodai on 17/8/16.
 */

public class WheelView extends View {

    private static final String TAG = WheelView.class.getSimpleName();

    private static final int START = 0;
    private static final int END = 1;
    private static final int GRADUALLY = 2;

    //旋转线程
    private Handler rotating = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START:
                    if (mRotaStatu == GRADUALLY)
                        break;
                    initDegree += mChangeInterval;
                    invalidate();
                    Message message = obtainMessage();
                    message.what = START;
                    sendMessageDelayed(message, 10);
                    break;
                case END:
                    mRotaStatu = END;
                    swichValue = "开始";
                    mChangeInterval = 10;
                    initDegree %= 360;
                    invalidate();
                    break;
                case GRADUALLY:
                    if (mRotaStatu == END)
                        break;
                    stopDrive--;
                    Log.i(TAG, ">>>now >>stopDrive>>>" + stopDrive);
                    Log.i(TAG, ">>>now >>randomValue>>>" + randomValue);
                    mChangeInterval = stopDrive / (randomValue / 10);
                    Log.i(TAG, ">>>now >>mChangeInterval>>>" + mChangeInterval);
                    if (mChangeInterval == 0) {
                        Message messageEnd = obtainMessage();
                        messageEnd.what = END;
                        sendMessage(messageEnd);
                        break;
                    }
                    initDegree += mChangeInterval;
                    invalidate();
                    Message messageGradually = obtainMessage();
                    messageGradually.what = GRADUALLY;
                    sendMessageDelayed(messageGradually, 10);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    //文字集合
    private String texts[] = {
            "小吕",
            "小张",
            "小邵",
            "小陈",
            "小杨",
            "小毛",
            "小孙",
            "小刘",
            "小冯",
            "小王",
            "你妹"
    };
    //图标集合
    private int drawables[] = {
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher
    };
    //扇形背景集合
    private int bgColors[] = {
            Color.BLACK,
            Color.BLUE,
            Color.DKGRAY,
            Color.CYAN,
            Color.GREEN,
            Color.GRAY,
            Color.RED,
            Color.YELLOW,
            Color.MAGENTA,
            Color.LTGRAY
    };


    //外环绘制画笔
    private Paint mRingPaint;
    //分割线画笔
    private Paint mCarveUpPaint;
    //按钮画笔
    private Paint mButtonPaint;
    //控件的高度
    private int height;
    //控件的长度
    private int width;
    //绘制的直径
    private int diameter;
    //绘制模块的数量
    private int count = 10;
    //模块角度
    private float fanSize;
    //扇形区间 rectf
    private RectF mFanRectF;
    //扇形半径
    private int fanRadius;
    //旋转的速率
    private float rate = 1;
    //初始度数
    private int initDegree = 0;
    //变化区间
    private int mChangeInterval = 10;
    //是不是在旋转
    private int mRotaStatu = END;
    //结束的随机值
    private int randomValue;
    //停止驱动值
    private int stopDrive = randomValue;
    //绘制文字的路径
    private Path paths[] = new Path[10];
    //文字所在弧长
    private double textArcLenght;


    public WheelView(Context context) {
        this(context, null);
    }

    public WheelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WheelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mRingPaint = new Paint();
        mCarveUpPaint = new Paint();
        mButtonPaint = new Paint();
        mCarveUpPaint.setAntiAlias(true);
        mRingPaint.setAntiAlias(true);
        mButtonPaint.setAntiAlias(true);
        mRingPaint.setStyle(Paint.Style.FILL);
        this.fanSize = 360f / count;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        this.width = getMeasuredWidth();
        this.height = getMeasuredHeight();
        this.diameter = width >= height ? height - 20 : width - 20;
        this.fanRadius = this.diameter / 2 - 30 - 3;
        int widthAndGeight[] = getWidthAndHeight("辅助", 36);
        this.textArcLenght = (this.diameter - 2 * (widthAndGeight[1] / 2 + 30)) * Math.PI / count;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCircle(canvas);
        drawFan(canvas);
        drawPointer(canvas);
        drawSwitch(canvas);
    }

    //绘制圆
    private void drawCircle(Canvas canvas) {
        //绘制实体圆
        mCarveUpPaint.setStyle(Paint.Style.FILL);
        mCarveUpPaint.setColor(Color.BLUE);
        canvas.drawCircle(this.width / 2, this.height / 2, this.diameter / 2, mCarveUpPaint);
        //绘制边界圆
        mCarveUpPaint.setColor(Color.WHITE);
        canvas.drawCircle(this.width / 2, this.height / 2, (this.diameter / 2) - 30, mCarveUpPaint);
    }

    //绘制扇形
    private void drawFan(Canvas canvas) {
        RectF oval = getFanRectf();
        for (int i = 0; i < count; i++) {
            mRingPaint.setColor(bgColors[i]);
            canvas.drawArc(oval, fanSize * i + initDegree, fanSize, true, mRingPaint);
            drawItemText(canvas, i, oval);
        }
    }

    //绘制按钮
    private String swichValue = "开始";

    private void drawSwitch(Canvas canvas) {
        mButtonPaint.setColor(Color.LTGRAY);
        canvas.drawCircle(this.width / 2, this.height / 2,
                (this.diameter / 4 / 2) * buttonChange, mButtonPaint);
        mButtonPaint.setTextSize(this.diameter / 16 * buttonChange);
        mButtonPaint.setColor(Color.WHITE);
        int widthAndGeight[] = getWidthAndHeight(swichValue, (int) (this.diameter / 16 * buttonChange));
        canvas.drawText(swichValue, this.width / 2 - widthAndGeight[0] / 2,
                this.height / 2 + widthAndGeight[1] / 2, mButtonPaint);
    }

    //绘制指针
    private void drawPointer(Canvas canvas) {
        mButtonPaint.setColor(Color.WHITE);
        Path path = new Path();
        path.moveTo(this.width / 2,
                this.height / 2 - this.diameter / 4 / 2 * buttonChange / 3 * 5);// 此点为多边形的起点
        path.lineTo(this.width / 2 - this.diameter / 4 / 2 * buttonChange / 5 * 2,
                this.height / 2 - this.diameter / 4 / 2 * buttonChange / 3 * 2);
        path.lineTo(this.width / 2 + this.diameter / 4 / 2 * buttonChange / 5 * 2,
                this.height / 2 - this.diameter / 4 / 2 * buttonChange / 3 * 2);
        path.close(); // 使这些点构成封闭的多边形
        canvas.drawPath(path, mButtonPaint);
    }

    //绘制文字
    private void drawItemText(Canvas canvas, int position, RectF oval) {
        if (paths[position] == null)
            paths[position] = new Path();
        int widthAndGeight[] = getWidthAndHeight(texts[position], 36);
        paths[position].reset();
        paths[position].addArc(oval, fanSize * position + fanSize / 2 - (int) (widthAndGeight[0] / textArcLenght * fanSize / 2)
                + initDegree, fanSize);
        mButtonPaint.setColor(Color.WHITE);
        mButtonPaint.setTextSize(36);
        canvas.drawTextOnPath(texts[position], paths[position], 0,
                widthAndGeight[1] + 30, mButtonPaint);
    }


    private float buttonChange = 1f;
    private float downX;
    private float downY;
    private boolean isClick = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mRotaStatu == GRADUALLY)
                    break;
                downX = event.getX();
                downY = event.getY();
                if (downX > this.width / 2 - this.diameter / 4 / 2 &&
                        downX < this.width / 2 + this.diameter / 4 / 2 &&
                        downY > this.height / 2 - this.diameter / 4 / 2 &&
                        downY < this.height / 2 + this.diameter / 4 / 2) {
                    buttonChange = 1.1f;
                    invalidate();
                    isClick = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                if (isClick) {
                    downX = event.getX();
                    downY = event.getY();
                    if (downX > this.width / 2 - this.diameter / 4 / 2 &&
                            downX < this.width / 2 + this.diameter / 4 / 2 &&
                            downY > this.height / 2 - this.diameter / 4 / 2 &&
                            downY < this.height / 2 + this.diameter / 4 / 2) {
                        isClick = false;
                        buttonChange = 1.0f;
                        Message message = rotating.obtainMessage();
                        if (mRotaStatu == END) {
                            message.what = START;
                            mRotaStatu = START;
                            swichValue = "停止";
                        } else if (mRotaStatu == START) {
                            message.what = GRADUALLY;
                            mRotaStatu = GRADUALLY;
                            swichValue = "执行";
                            randomValue = getRandomValue();
                            stopDrive = randomValue;
                        }
                        rotating.sendMessage(message);
                    }else {
                        isClick = false;
                        buttonChange = 1.0f;
                        invalidate();
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }

    //获取文字的长度
    private int[] getWidthAndHeight(String value, int size) {
        Paint paint = new Paint();
        paint.setTextSize(size);
        Rect rect = new Rect();
        //返回包围整个字符串的最小的一个Rect区域
        paint.getTextBounds(value, 0, value.length(), rect);
        return new int[]{rect.width(), rect.height()};
    }


    //扇形区间 rectf
    private RectF getFanRectf() {
        if (mFanRectF == null)
            mFanRectF = new RectF(this.width / 2 - fanRadius,
                    this.height / 2 - fanRadius,
                    this.width / 2 + fanRadius,
                    this.height / 2 + fanRadius);
        return mFanRectF;
    }


    //减速的时候的随机数
    private int getRandomValue() {
        Random r = new Random();
        return r.nextInt(150) % (150 - 100 + 1) + 100;
    }

}
